<template>
  <div>
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <template v-for="(item, index) in formList">
        <el-form-item v-show="item.show == null || item.show === true"
                      :key="`${item.prop}${index}`"
                      :style="item.itemStyle || {}"
                      :label="item.name"
                      :prop="item.prop"
                      :class="item.itemClass"
        >
          <component
            :is="item.componentType || 'el-input'"
            :style="item.style || {}"
            :value-format="item.valueFormat || {}"
            v-if="item.prop"
            v-model="formData[item.prop]"
            :clearable="true"
            :class="item.class"
            v-bind="item.attrConfig || {}"
            @change="handlerSelectData(item)"
            @changeImg="changeImg"
          >
            <template v-for="option in item.optionList">
              <el-radio :label="option.value">{{ option.label }}</el-radio>
            </template>
          </component>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import AddImg from '@/components/PopItems/add-img.vue'

export default {
  name: 'AddEnergyCategory',
  mixins: [dictMixin],
  components: { AddImg },
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      isAdd: true,
      formData: {},
      maxRemarkLength: 200,
      formList: [
        {
          name: '名称',
          prop: 'name',
          attrConfig: { placeholder: '请输入名称' }
        }, {
          name: '图片',
          prop: 'logo',
          componentType: 'AddImg',
          attrConfig: { tip: ' ' }
        }, {
          name: '位置',
          prop: 'position',
          componentType: 'el-radio-group',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'MiniProgramCarouseImagePosition'
          },
          attrConfig: {
            placeholder: '请选择位置',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        }, {
          name: '类型',
          prop: 'type',
          componentType: 'el-radio-group',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'MiniProgramCarouseImageType'
          },
          attrConfig: {
            placeholder: '请选择类型',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        }, {
          name: '链接',
          prop: 'link',
          show: false,
          attrConfig: { placeholder: '请输入链接' }
        }, {
          name: '排序',
          prop: 'sort',
          attrConfig: { placeholder: '请输入排序' }
        }
      ]
    }
  },
  computed: {
    rules() {
      return {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 50, message: '名称最长50字符', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请选择位置', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        this.isAdd = !data.id
        this.formList.forEach((e) => {
          this.$set(this.formData, e.prop, data[e.prop])
        })
        this.$set(this.formData, 'id', data.id)
        this.formList[4].show = this.formData.type === '2'
        if (data.logo) {
          this.formList[1].attrConfig.defaultFileList = [data.logo]
        }
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      this.submit(params)
    }
  },
  methods: {
    changeImg(key, value) {
      this.$set(this.formData, 'logoFile', value)
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
      if (config.prop === 'type') {
        this.formList[4].show = this.formData.type === '2'
        if (!this.formList[4].show) {
          this.formData.link = null;
        }
      }
    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.formData.logoFile) {
            const formData = new FormData()
            formData.append('file', this.formData.logoFile.raw)
            const urlRes = await this.$api.fileManage.baseUploadData(
              '/energy-carbon/grass-file/file/upload',
              formData
            )
            if (Number(urlRes.code) === 1000) {
              params.logo = urlRes.data
            }
          }
          const res = await this.$api.miniProgramCarouseImage[this.isAdd ? 'add' : 'update'](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'miniProgramCarouseImage-add')
          }
        }
      })
    }
  }
}
</script>
